<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="文件名称" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="文件类型" prop="fileTypeValue">
        <el-select v-model="queryParams.fileTypeValue" placeholder="请选择文件类型" clearable>
          <el-option v-for="dict in dict.type.sys_file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="文件状态" prop="statusValue">
        <el-select v-model="queryParams.statusValue" placeholder="请选择文件状态" clearable>
          <el-option v-for="item in statusList" :key="dict.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:file:bindingRecord:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['vehicle:driver:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table fit v-loading="loading" border :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件名称" prop="fileName" :show-overflow-tooltip="true">
        <!-- <template slot-scope="scope">
            <el-link @click="handleDetailDiag(scope.row)" type="primary">{{
              scope.row.fileName
            }}</el-link>
          </template> -->
      </el-table-column>
      <el-table-column label="编号" prop="fileCode" :show-overflow-tooltip="true" width="150">
          <template slot-scope="scope">
            <el-link @click="handleDetail(scope.row)" type="primary">{{
              scope.row.fileCode
            }}</el-link>
          </template>
      </el-table-column>
      <el-table-column label="状态" prop="statusValue" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.statusValue == '1' ? '申请中' : scope.row.statusValue == '2' ? '装订中' : scope.row.statusValue ==
            3 ? '拒绝' : scope.row.statusValue == 4 ? '收到原始记录' : scope.row.statusValue == 5 ? '申请人领取' :
              scope.row.statusValue == 6 ? '已领取' : scope.row.statusValue == 7 ? '重新装订':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录编号" prop="fileBindCode" :show-overflow-tooltip="true" width="150"></el-table-column>
      <el-table-column label="页数" prop="numLabel" :show-overflow-tooltip="true" width="150"></el-table-column>

      <el-table-column label="打印方式" prop="printStyleLabel" :show-overflow-tooltip="true" />
      <el-table-column label="胶装方向" prop="clueDirectionLabel" :show-overflow-tooltip="true" />
      <el-table-column label="装订日期" prop="bindTime" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="流水号" prop="fileBindCode"  :show-overflow-tooltip="true" /> -->
      <el-table-column :show-overflow-tooltip="true" align="center" label="经办人" prop="createByName" />
      <el-table-column label="领用日期" prop="receiveTime" :show-overflow-tooltip="true" />
      <el-table-column label="重新装订原因" prop="reason" :show-overflow-tooltip="true" />

      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" v-if="scope.row.statusValue == 1" type="text"
            v-hasPermi="['system:file:bindingRecord:agree']" @click="handleRefuseAgree(scope.row, 1)">同意</el-button>
          <el-button size="mini" v-if="scope.row.statusValue == 1" type="text"
            v-hasPermi="['system:file:bindingRecord:refuse']" @click="handleRefuseAgree(scope.row, 2)">拒绝</el-button>
          <el-button size="mini" v-if="scope.row.statusValue == 2" type="text"
            v-hasPermi="['system:file:bindingRecord:complete']" @click="handleRefuseAgree(scope.row, 1)">装订完成</el-button>
          <el-button size="mini" v-if="(scope.row.statusValue == 4 || scope.row.statusValue == 7)&&!scope.row.receiveTime" type="text"
            v-hasPermi="['system:file:bindingRecord:receive']"
            @click="handleRefuseAgreeReceive(scope.row, 1)">领取</el-button>
          <el-button size="mini" v-if="scope.row.statusValue == 5" type="text"
            v-hasPermi="['system:file:bindingRecord:add']" @click="handleAgain(scope.row)">重新装订</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <el-dialog :visible.sync="showCode" title="领用二维码" width="300px" append-to-body>
      <div style="text-align: center">
        <vue-qr :text="textUrl" :size="200"></vue-qr>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showBinding" title="重新装订" width="500px" append-to-body>
      <el-form ref="formBinding" :model="formBinding" :rules="rules" label-width="120px">
        <el-form-item label="重新装订原因" prop="reason">
          <!-- <div style="display: flex;align-items: center;justify-content: center;font-size: 20px;">确定要领用当前二维码吗？</div> -->
          <el-input v-model="formBinding.reason" placeholder="请输入重新装订原因" clearable :style="{ width: '100%' }">
          </el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button size="mini" @click="showBinding = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveBinding">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="领取" :visible.sync="receiveShow" width="30%" :before-close="handleClose">
      <el-form ref="elForm" :disabled="$route.query.isInfo" :model="formData" :rules="rules" size="medium"
        label-width="120px">
        <el-form-item label="领用日期" prop="receiveTime">
          <el-date-picker v-model="receiveTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }"
            placeholder="请选择领用日期" clearable></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subReceive">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 打印模板位置 -->
    <PrintBox :pageNum="queryParams.pageNum" :total="total" :printRow="printList" :checkNum="18"
      :checkLabel="'contentList'" id="printBox">
      <template slot="title" slot-scope="scope">
        试验室受控文件清单 STET/B/03-8
        <div style="font-size: 14px; margin-top: 5px">
          <span v-if="zlcode.includes(Number(fileTypeValue))">（质量活动记录表格 （通用类、标定类、各类试验物质及设备验收类、
            辅助类、期间核查类）</span>

          <span v-if="wlwjcode.includes(Number(fileTypeValue))">(往来文件(本公司发文、上级单位来文、外单位来文))</span>
          <span v-if="[6, 15, 16].includes(Number(fileTypeValue))">(质量手册、资源手册、程序文件)</span>
          <span v-if="[7, 8, 10, 11, 12, 113, 14].includes(Number(fileTypeValue))">(作业指导书)</span>
          <span
            v-if="[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(Number(fileTypeValue))">(质量活动记录表格（原始观测数据、记录、检测报告）)</span>
          <span v-if="fileTypeValue == 22">(检测方法)</span>
        </div>
      </template>
      <template slot-scope="scope" style="position: relative;">
        <div style="position: absolute; top: 100px;left: 200px;">
          <img src="../../../assets/images/watermark.png" alt="" style="width: 200px;height: 80px;">
        </div>
        <!-- 表格  class  table-page  必须-->
        <table style="border-collapse: collapse" border="1" cellspacing="0" class="table-page">
          <thead>
            <tr class="table_header">
              <th style="width: 20mm">序号</th>
              <th style="width: 30mm">受控编号</th>
              <th style="width: 45mm">文件名</th>
              <th style="width: 65mm">文件类型</th>
              <th style="width: 55mm">文件状态</th>
              <th style="width: 50mm">文件废止日期</th>
              <th style="width: 50mm">文件实施日期</th>
              <th style="width: 50mm">备注</th>
              <!-- <th
                  style="width: 50mm"
                  v-if="wlwjcode.includes(Number(fileTypeValue))"
                >
                  文件下发日期
                </th> -->
            </tr>
          </thead>
          <!-- 同列表接口数据 -->
          <tbody>
            <tr v-for="(e, i) in 18">
              <td>
                {{ scope.item.contentList[i] ? i + 1 : "" }}
              </td>
              <td>
                {{
                  (scope.item.contentList[i] &&
                    scope.item.contentList[i].fileCode) ||
                  ""
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].fileName
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].collectUserName
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  scope.item.contentList[i].status
                }}
              </td>

              <td>
                {{
                  scope.item.contentList[i] &&
                  parseTime(scope.item.contentList[i].endDate, "{y}-{m}-{d}")
                }}
              </td>
              <td>
                {{
                  scope.item.contentList[i] &&
                  parseTime(scope.item.contentList[i].createTime, "{y}-{m}-{d}")
                }}
              </td>
              <td></td>
              <!-- <td v-if="wlwjcode.includes(Number(fileTypeValue))">
                  {{
                    scope.item.contentList[i] &&
                    parseTime(scope.item.contentList[i].createTime, "{y}-{m}-{d}")
                  }}
                </td> -->
            </tr>
          </tbody>
        </table>
      </template>
    </PrintBox>
    <!-- <Detail ref="Detail" :id="id"></Detail> -->
  </div>
</template>
<script>
import store from "@/store";
import printStyle from "@/utils/print.js";
import { listFileBindRecord, auditFileBindRecord, fileBindRecordAdd } from "@/api/system/bindingRecord.js"
import { listFileManager, delFileManager } from "@/api/system/fileManager.js";
import { fileGetAdd } from "@/api/system/fileManagerRecord.js";
//   import Detail from "./detail.vue";
export default {
  name: "listFileManager",
  components: {
    //   Detail,
  },
  dicts: ["sys_file_type", "sys_file_status"],
  data() {
    return {
      statusList:[
        {label:'申请中',value:'1'},
        {label:'装订中',value:'2'},
        {label:'拒绝',value:'3'},
        {label:'收到原始记录',value:'4'},
        {label:'申请人领取',value:'5'},
        {label:'重新装订',value:'7'},
      ],
      receiveShow: false,
      baseUrl: this.$VUE_APP_IMG_API,
      id: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      dataList: [],
      // 弹出层标题
      // 日期范围
      dateRange: [],
      // 数据范围选项
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      showBinding: false,
      showCode: false,
      current: {},
      showSend: false,
      receiveTime: '',
      form: {},
      rules: {
        typeValue: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
        num: [
          {
            required: true,
            message: "输入数量",
            trigger: "blur",
          },
        ],
      },
      formBinding: {},
      textUrl: "",
      infos: [],
      printList: [],
      fileTypeValue: 0,
      zlcode: [21, 20, 19, 18, 17], //质量活动记录表格
      wlwjcode: [2, 3, 4, 5], //外来文件
      fileBindRecordId: ''
    };
  },
  // 22--
  created() {
    this.getList();
  },
  methods: {
    printBox() {
      //infos  勾选的数据 如果有勾选就打印勾选。
      if (this.infos.length) {
        this.printList = [
          {
            contentList: this.infos,
          },
        ];
      } else {
        //反之打印当前整个列表
        this.printList = [
          {
            contentList: this.dataList,
          },
        ];
      }
      // 7, 8, 10, 11, 12, 113, 14
      // 6, 15, 16
      // zlcode
      // wlwjcode
      let flag = false;
      let e = this.printList[0].contentList[0].fileTypeValue;
      if ([7, 8, 10, 11, 12, 113, 14].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => ![7, 8, 10, 11, 12, 113, 14].includes(Number(e.fileTypeValue))
        );
      } else if ([6, 15, 16].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => ![6, 15, 16].includes(Number(e.fileTypeValue))
        );
      } else if (this.zlcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => !this.zlcode.includes(Number(e.fileTypeValue))
        );
      } else if (this.wlwjcode.includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => !this.wlwjcode.includes(Number(e.fileTypeValue))
        );
      } else if ([23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(Number(e))) {
        flag = this.printList[0].contentList.some(
          (e) => ![23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34].includes(Number(e.fileTypeValue))
        );
      }
      if (flag) {
        this.$modal.msgWarning("多选数据 请保持类型一致");
        return;
      }
      this.fileTypeValue = this.printList[0].contentList[0].fileTypeValue;

      setTimeout(() => {
        this.$print({
          printable: "printBox", //打印区域id
          type: "html", //打印类型是html
          scanStyles: false,
          targetStyles: ["*"],
          style: this.workStyle(),
        });
      }, 500);
    },
    // 同意拒绝
    handleRefuseAgree(e, i) {
      this.$modal.confirm(` ${e.statusValue == 1 ? i == 1 ? '确定要同意此文件吗?' : '确定要拒绝此文件吗?' : e.statusValue == 2 ? '确认收到原始文件吗？' : e.statusValue == 4 ? '确定要领取文件吗？' : ''}`).then(() => {
        auditFileBindRecord({ fileBindRecordId: e.fileBindRecordId, optType: i, preAudit: e.statusValue }).then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess("操作成功")
            this.getList();
          }
        })
      })
        .catch(() => { });
    },
    // 领取
    handleRefuseAgreeReceive(e, i) {
      this.receiveTime = this.parseTime(new Date().getTime(), "{y}-{m}-{d}")
      this.receiveShow = true,
        this.fileBindRecordId = e.fileBindRecordId
    },
    subReceive() {
      auditFileBindRecord({ fileBindRecordId: this.fileBindRecordId, optType: 1, preAudit: 4, reason: this.receiveTime }).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("操作成功")
          this.getList();
        }
      })
      this.receiveShow = false
    },
    // 可以自定义样式  printStyle 是公共样式 切勿私自修改
    workStyle() {
      return `${printStyle}
           table,
        table tr th,
        table tr td {
          height: 10mm;
          padding:7px
        }
        tr {
          page-break-inside: avoid;
        }
        .table_header{
          font-size:16px;
        }
        `;
    },
    changeUser(e) {
      this.formBinding.user = e.nickName;
    },
    handleAgain(e) {
      this.showBinding = true
      this.formBinding = e
      this.formBinding.upperId = e.fileBindRecordId
      delete this.formBinding.fileBindRecordId
    },
    saveBinding() {
      this.formBinding.statusValue = "7"
      this.formBinding.receiveTime = ''
      this.formBinding.bindTime = this.parseTime(new Date().getTime(), "{y}-{m}-{d}")
      fileBindRecordAdd(this.formBinding).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("申请成功");
          this.showBinding = false
          this.getList();
        }
      })
    },
    saveSend() {
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      // (this.form.fileManagerId = this.current.fileManagerId),
      //   fileGetAdd(this.form).then((response) => {
      //     this.$modal.msgSuccess("操作成功");
      //     this.showSend = false;
      //     this.getList();
      //   });
      // }
      // });
    },
    handleSend(e) {
      this.form = {};
      this.current = e;
      this.showSend = true;
    },

    handleAddHistory(e) {
      this.form = {};
      this.current = e;
      // this.showSend = true;
      this.form.fileManagerId = this.current.fileManagerId
      this.form.num = '1'
      this.$alert('确定要领用当前二维码吗？', '领用', {
        confirmButtonText: '确定',
        callback: action => {
          fileGetAdd(this.form).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.showSend = false;
            this.getList();
          });
        }
      });
      // }
    },
    userSelect() {
      userSelect().then((response) => {
        this.userList = response.data;
      });
    },
    // 获取文件名称
    getFileName(name) {
      console.log(name);
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    getList() {
      this.loading = true;
      listFileBindRecord(
        this.queryParams
      ).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.typeValue = data.value;
      this.handleQuery();
    },
    handleExport() {
      this.queryParams.ids = this.queryParams.ids.toString()
      this.download(
        "/system/fileBindRecord/export",
        {
          ...this.queryParams,
        },
        `装订记录_${this.parseTime(
          new Date().getTime(),
          "{y}-{m}-{d}"
        )}.xlsx`
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDetail(row) {
      this.$router.push("./addbinding?isInfo=true&id=" + row.fileBindRecordId);
    },
    handleDetailDiag(e) {
      this.$refs.Detail.show(e.fileManagerId);
    },
    handleCode(res) {
      this.textUrl =
        process.env.VUE_APP_CODE_API + "fileManager?id=" + res.fileManagerId;
      this.showCode = true;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.fileManagerId);
      this.queryParams.ids = selection.map((item) => item.fileBindRecordId);
      this.infos = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("./addbinding");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const configId = row.fileManagerId || this.ids;
      this.$router.push("./addFile?isEdit=true&id=" + configId);
    },
    // handleExport() {
    //   this.download(
    //     "system/fileManager/export",
    //     {
    //       ...this.queryParams,
    //     },
    //     `文件记录表_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}")}.xlsx`
    //   );
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.fileManagerId || this.ids;
      let name = this.checkRow(
        userIds,
        this.dataList,
        "fileManagerId",
        "DELETE",
        "fileName"
      );
      this.$modal
        .confirm('是否确认删除文件名称为"' + name + '"的数据项？')
        .then(function () {
          return delFileManager(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
  